# coding=utf-8
from django.shortcuts import render

# Create your views here.
from django.views.decorators.cache import cache_page

from archive_classes.models import ArchiveClasses, ClassesKeyWord
from common.requests import *
from django.core.cache import cache


def classes_index(request):
    """
    首页
    :param request:
    :return:HttpResponse
    """
    try:
        if not cache.has_key("default_archive"):
            cache.set("default_archive", 0)
        default_archive = cache.get("default_archive")
        
        if not cache.has_key("smart_archive"):
            cache.set("smart_archive", 0)
        smart_archive = cache.get("smart_archive", 0)
        
        return render(request, template_name="archive_classes/list.html",
                      context={"default_archive": default_archive, "smart_archive": smart_archive})
    except Exception as e:
        print e
        return err_requests("500")


def default_archive_api(request):
    """
    默认归档设置
    :param request:
    :return:JsonResponse
    """
    try:
        body = get_body(request)
        cache.set("default_archive", 1 if body.get("default_archive") else 0)
        return success_requests()
    except Exception as e:
        print e
        return err_requests("500")


def smart_archive_api(request):
    """
    智能归档设置
    :param request:
    :return:JsonResponse
    """
    try:
        body = get_body(request)
        cache.set("smart_archive", 1 if body.get("smart_archive") else 0)
        return success_requests()
    except Exception as e:
        print e
        return err_requests("500")


def classes_list(request):
    """
    分类列表视图
    :param request: 
    :return: HttpResponse
    """
    try:
        classes = ArchiveClasses.objects.all()
        object_list = []
        for classe in classes:
            object = {}
            object["id"] = classe.id
            object["name"] = classe.name
            object["code"] = classe.code
            object["sort"] = classe.sort
            keywords = list(ClassesKeyWord.objects.filter(archive_id=classe.id).values("words"))
            if len(keywords):
                object["keywords"] = ",".join([keyword.get("word") for keyword in keywords])
            object_list.append(object)
        return render("archive_classes/list.html", {"object_list": object_list})
    except Exception as e:
        print e
        return err_requests("500")


def classes_list_api(request):
    """
    分类列表API
    :param request:
    :return:JsonResponse
    """
    try:
        classes = ArchiveClasses.objects.all()
        result = []
        for classe in classes:
            object = {}
            object["id"] = classe.id
            object["name"] = classe.name
            object["code"] = classe.code
            object["sort"] = classe.sort
            keywords = list(ClassesKeyWord.objects.filter(archive_id=classe.id).values("word"))
            if len(keywords):
                object["keywords"] = ",".join([keyword.get("word") for keyword in keywords])
            result.append(object)
        return success_requests(result)
    except Exception as e:
        print e
        return err_requests("500")


def classes_info_api(request):
    """
    类别信息
    :param request:
    :return:JsonResponse
    """
    try:
        body = get_body(request)
        if isinstance(body, JsonResponse):
            return body
        body_params = get_params(body, {"id": "id"})
        if isinstance(body_params, JsonResponse):
            return body_params
        id = body_params.get("id")
        
        classes = ArchiveClasses.objects.filter(id=id)
        result = []
        for classe in classes:
            object = {}
            object["id"] = classe.id
            object["name"] = classe.name
            object["code"] = classe.code
            object["sort"] = classe.sort
            keywords = list(ClassesKeyWord.objects.filter(archive_id=classe.id).values("word"))
            if len(keywords):
                object["keywords"] = ",".join([keyword.get("word") for keyword in keywords])
            result = object
            break
        return success_requests(result)
    except Exception as e:
        print e
        return err_requests("500")


def classes_update_api(request):
    """
    更新类别
    :param request:
    :return:JsonResponse
    """
    try:
        body = get_body(request)
        if isinstance(body, JsonResponse):
            return body
        class_params = get_params(body, {"id": "id", "code": "code", "sort": "sort","name":"name"}, {"keywords": "keywords"})
        if isinstance(class_params, JsonResponse):
            return body
        
        id = class_params.get("id")
        keywords = class_params.get("keywords")
        if len(keywords):
            keywords = keywords.split(",")
            del class_params['keywords']
        
        classes = ArchiveClasses.objects.filter(id=id)
        count = classes.update(**class_params)
        for classe in classes:
            ClassesKeyWord.objects.filter(archive_id=classe.id).delete()
            for keyword in keywords:
                ClassesKeyWord.objects.create(word=keyword, archive_id=classe)
            break
        return success_requests({"count": count})
    except Exception as e:
        print e
        return err_requests("500")


def classes_delete_api(request):
    """
    删除类别
    :param request:
    :return:JsonResponse
    """
    try:
        body = get_body(request)
        if isinstance(body, JsonResponse):
            return body
        class_params = get_params(body, {"id": "id"})
        if isinstance(class_params, JsonResponse):
            return body
        id = class_params.get("id")
        
        count = ArchiveClasses.objects.filter(id=id).delete()
        return success_requests({"count": count})
    except Exception as e:
        print e
        return err_requests("500")


def classes_add_api(request):
    """
    添加类别
    :param request:
    :return:JsonResponse
    """
    try:
        body = get_body(request)
        if isinstance(body, JsonResponse):
            return body
        class_params = get_params(body, {"name": "name", "code": "code", "sort": "sort"}, {"keywords": "keywords"})
        if isinstance(class_params, JsonResponse):
            return body
        
        keywords = class_params.get("keywords")
        if len(keywords):
            keywords = keywords.split(",")
            del class_params['keywords']
        
        classes = ArchiveClasses.objects.create(name=class_params.get("name"), code=class_params.get("code"),
                                                sort=class_params.get("sort"))
        
        for keyword in keywords:
            ClassesKeyWord.objects.create(word=keyword, archive_id=classes)
        
        return success_requests()
    except Exception as e:
        print e
        return err_requests("500")
